import 'package:dio/dio.dart' as dio;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';
import 'package:management/const/consts.dart';
import 'package:management/const/init.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/demand/request/CreateDemandOrTaskRequestParams.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/toast.dart';
import 'package:management/generated/assets.dart';
import 'package:management/page/ModuleProject/demand_or_task_detail_screen/logic.dart';
import 'package:management/page/ModuleProject/project_detail_screen/logic.dart';

import 'state.dart';

class CreateDemandScreenLogic extends GetxController {
  final CreateDemandScreenState state = CreateDemandScreenState();

  @override
  void onInit() {
    super.onInit();
    _initData();
  }

  void selectStatus() {
    Get.bottomSheet(
        Wrap(
            children: List<Widget>.generate(5, (index) {
          return Container(
            padding: const EdgeInsets.symmetric(vertical: 2),
            width: double.infinity,
            height: 60,
            child: TextButton(
              onPressed: () {
                if (index == 4) {
                  Get.back();
                  return;
                }
                state.demandStatus.value = index;
                state.statusController.text =
                    state.listDemandState[state.demandStatus.value]!;
                Get.back();
              },
              style: Theme.of(Get.context!).textButtonTheme.style,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    index == 4 ? MyText.cancel : state.listDemandState[index]!,
                    style: Theme.of(Get.context!).textTheme.bodyLarge?.copyWith(
                        color: index == 4
                            ? MyColor.error
                            : MyColor.grayScale[500]),
                  ),
                ],
              ),
            ),
          );
        })),
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void selectPriority() {
    Get.bottomSheet(
        Wrap(
            children: List<Widget>.generate(5, (index) {
          return Container(
            padding: const EdgeInsets.symmetric(vertical: 2),
            width: double.infinity,
            height: 60,
            child: TextButton(
              onPressed: () {
                if (index == 4) {
                  Get.back();
                  return;
                }
                state.demandPriority.value = index;
                state.priorityStatusController.text =
                    state.listDemandPriority[state.demandPriority.value]!;
                Get.back();
              },
              style: Theme.of(Get.context!).textButtonTheme.style,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    index == 4
                        ? MyText.cancel
                        : state.listDemandPriority[index]!,
                    style: Theme.of(Get.context!).textTheme.bodyLarge?.copyWith(
                        color: index == 4
                            ? MyColor.error
                            : MyColor.grayScale[500]),
                  ),
                ],
              ),
            ),
          );
        })),
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  selectCharge() {
    MyHttpClient.getAllCompanyUser().then((value) {
      if (value.code == 200) {
        state.listNumbers.value = value.data!;
        Get.bottomSheet(
            Flexible(
              child: ListView.builder(
                itemBuilder: (context, index) {
                  return SizedBox(
                    height: 50,
                    child: ListTile(
                      leading: ClipOval(
                        child: FadeInImage(
                          image: NetworkImage(state.listNumbers[index].avatar ??
                              GlobalInit.headImage),
                          height: 45.w,
                          width: 45.h,
                          fit: BoxFit.fill,
                          placeholderFit: BoxFit.scaleDown,
                          placeholder: const AssetImage(Assets.iconAvator),
                        ),
                      ),
                      title: Text(
                        state.listNumbers[index].nickname ?? MyText.loading,
                        style: Theme.of(Get.context!).textTheme.titleSmall,
                      ),
                      subtitle: Text(
                        state.listNumbers[index].realName ?? MyText.loading,
                        style: Theme.of(Get.context!).textTheme.bodyMedium,
                      ),
                      onTap: () {
                        state.chargeUrl.value =
                            state.listNumbers[index].avatar ??
                                GlobalInit.headImage;
                        state.chargeId.value =
                            state.listNumbers[index].id.toString();
                        Get.back();
                      },
                    ),
                  );
                },
                itemCount: state.listNumbers.length,
              ),
            ),
            shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
            backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
  }

  void addAttachments() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      allowMultiple: true,
      // allowedExtensions: ['docx', 'pdf', 'doc', 'ppt', 'pptx', 'txt', 'md'],
    );

    if (result != null) {
      state.listAttachFiles.value = result.files;
      state.listAttachFiles.refresh();
    } else {
      Utils.toastError('File not found');
    }
  }

  submit() {
    if (state.taskTitle.isEmpty) {
      Utils.toastWarning(
          MyText.xCantBeNull.trParams({'x': MyText.taskTitle.tr}));
      return;
    }
    _realSubmit();
  }

  void _realSubmit() async {
    LoadingElement.loadingDialog(true);
    if (state.listAttachFiles.isNotEmpty) {
      List<dio.MultipartFile> attachFiles = state.listAttachFiles
          .map((e) => dio.MultipartFile.fromFileSync(e.path!, filename: e.name))
          .toList();
      state.listAttachmentsParams.clear();
      await MyHttpClient.uploadFiles(attachFiles).then((value) {
        if (value.code == 200) {
          state.listAttachmentsParams.value = value.data!
              .map((e) => Attachments(filename: e.name, url: e.url))
              .toList();
        } else {
          Get.back();
          Utils.toastError(value.msg);
          return;
        }
      }).onError((error, stackTrace) {
        Get.back();
        Utils.toastError(error);
        return;
      });
    }
    var params = CreateDemandOrTaskRequestParams(
        projectId: state.projectId == 0 ? null : state.projectId,
        pid: state.pid == 0 ? null : state.pid,
        priority: state.demandPriority.value,
        name: state.taskTitle.value,
        description: state.demandDescription.value,
        startTime: state.taskStartTime.value,
        endTime: state.taskEndTime.value,
        type: state.pid == 0 ? 0 : 1,
        status: state.demandStatus.value,
        chargeId: int.parse(state.chargeId.value),
        attachments: state.listAttachmentsParams);
    await MyHttpClient.createDemandOrTask(params).then((value) {
      if (value.code == 200) {
        Get.back();
        state.pid == 0
            ? Get.find<ProjectDetailScreenLogic>().refreshProjectDetailPage()
            : Get.find<DemandOrTaskDetailScreenLogic>()
                .refreshDemandOrTaskDetailPage();
        Get.back();
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
  }

  void _initData() {}
}
